<template>
  <div>
    <div>
      {{ formData }}
      <h2>投放区域</h2>
      <el-select :model-value="selectArr" multiple @change="selectChange">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <detailTable :formData="formData" :optionsMap="optionsMap" />
    <crowdEdit ref="crowdRef" />
    <div>
      <el-button @click="submit">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import detailTable from '@/components/form/detailTable.vue'
import crowdEdit from '@/components/form/crowdEdit.vue'
import { computed, onMounted, ref } from 'vue'

const crowdRef = ref(null)
const formData = ref([])
const submit = () => {
  const crowdArr = crowdRef.value.crowdArr
  console.log(crowdArr);
  formData.value.forEach(item => {
    item.crowd = crowdArr
  })
  console.log("formData", formData.value);
}
//下拉框显示值
const selectArr = computed(() => {
  return formData.value.map(item => item.name)
})
//下拉框值改变事件
const selectChange = (val) => {
  console.log(val);

  const _arr = val.map((code) => {
    let isExit = false
    formData.value.forEach(item => {
      if (code === item.name) {
        isExit = item
      }
    })
    if (isExit) {
      return isExit
    } else {
      return {
        name: code,
        details: {
          duty: '',
        },
        crowd: []
      }
    }
  })
  formData.value = _arr
  console.log(formData.value);
}

onMounted(()=>{
  //回显
  setTimeout(() => {
    formData.value = [
      {
        "name": "app-header",
        "details": {
          "duty": "张三"
        },
        "crowd": [
          {
            "crowdName": "小李",
            "crowdSize": "100W"
          },
          {
            "crowdName": "小王",
            "crowdSize": "200W"
          }
        ]
      },
      {
        "name": "app-footer",
        "details": {
          "duty": "李四"
        },
        "crowd": [
          {
            "crowdName": "小李",
            "crowdSize": "100W"
          },
          {
            "crowdName": "小王",
            "crowdSize": "200W"
          }
        ]
      }
    ]

    crowdRef.value.setCrowdArr(formData.value[0].crowd)

  }, 1000)
})

const options = [
  {
    value: 'app-header',
    label: '头部'
  },
  {
    value: 'app-banner',
    label: '首页banner'
  },
  {
    value: 'app-footer',
    label: '底部'
  },
]

const optionsMap = {}
options.map((item) => {
  optionsMap[item.value] = item.label
})
</script>

<style scoped></style>
